<?php
/**
 * FUserController.class.php
 * 前台用户控制器(FrontUser)
 *
 * @author 王中艺 <[email address]>
 * @date 	2017-02-10
 */

namespace Admin\Controller;
use Common\Model\UserModel as BaseFUserModel;

class FUserController extends BaseController {

	/**
	 * 获取用户列表
	 * @param   $p    页码数
	 * @param   $sort   排序
	 * @param   $desc     是否倒序
	 * @param   $keyword 关键词
	 * @return  list(varname)
	 */
	function list(){
		$page 	= $this->iInfo['p'] ? $this->iInfo['p'] : 1;
		$sort 	= $this->iInfo['sort'];
		$desc 	= $this->iInfo['desc'];
		$keyword 	= $this->iInfo['keyword'];
		$fatherId 	= $this->iInfo['father_id'];
		$timeS 	= $this->iInfo['date_start'] ? strtotime($this->iInfo['date_start']) : false;
		$timeE 	= $this->iInfo['date_end'] ? strtotime($this->iInfo['date_end'].' +1 day') : false;

		//关键词分析
		if(in_array($keyword, BaseFUserModel::ROLE_MAP)){
			$roleMap 	= array_flip(BaseFUserModel::ROLE_MAP);
			$roleId 	= $roleMap[$keyword];
			$keyword 	= false;
		}

		$list 	= D('FUser')->getList(
			$keyword, $roleId, $sort, $desc, $page, 
			$timeS, $timeE, $fatherId, $pageHtml, $count
		);

		$this->response([
			'list' => $list, 
			'page_html' => $pageHtml, 
			'count' => $count
		]);
	}

	/**
	 * 获取VIP用户列表
	 * @param 	$p 	页码数
	 * @return 	$list
	 */
	function getVipList(){
		$keyword 	= $this->request('keyword', false);
		$sort 	= $this->request('sort');
		$desc 	= $this->request('desc');
		$page 	= $this->request('p', 1);
		$pageHtml 	= true;

		$list 	= D('FUser')->getVipList($keyword, $sort, $desc, $page, $pageHtml);
		if($list === false)
			$this->outOInfo(D('FUser')->errMsg, 0);
		$this->outOInfo(['list' => $list, 'page_html' => $pageHtml]);
	}

	/**
	 * 获取用户详情信息
	 * @param   $user_id 用户ID
	 * @return  用户数据
	 */
	function detail(){
		$this->unEmptyParam(array('user_id'));
		$userId 	= $this->iInfo['user_id'];

		$userInfo 	= D('FUser')->getUserInfo($userId);
		$relaInfo 	= D('FUser')->getRelaInfo($userId);
		$this->outOInfo(array('user_info' => $userInfo, 'rela_info' => $relaInfo));
	}

	/**
	 * 保存用户信息
	 * @param   $user_id 用户ID
	 * @param   $role_id 角色ID
	 * @param   $father_id 上级ID
	 * @param   $mobile 手机号
	 * @param   $truename 真实姓名
	 */
	function save(){
		$this->unEmptyParam(['user_id']);

		$userId 	= $this->request('user_id');
		$roleId 	= $this->request('role_id', false);
		$fatherId 	= $this->request('father_id', false);
		$mobile 	= $this->request('mobile', false);
		$truename 	= $this->request('truename', false);
		$childSchool	= $this->request('child_school');
		$childCourseName 	= $this->request('child_course_name');

		$userInfo 	= D('FUser')->getUserInfo($userId);
		$model 	= new \Think\Model();
		$model->startTrans();
		try{
			//变更用户角色
			if($roleId && $roleId != $userInfo['role_id']){
				$User 	= new \Wechat\Model\UserModel();
				$ret 	= $User->changeUserRole($userId, $roleId);
				if($ret === false){
					E($User->errMsg);
				}
			}

			//更改信息
			$userInfo['role_id']	= $roleId;
			$userInfo['mobile']		= $mobile;
			$userInfo['truename']	= $truename;
			$userInfo['child_school']	= $childSchool;
			$userInfo['child_course_name']	= $childCourseName;
			if(!D('FUser')->changeUserInfo($userId, $userInfo)){
				E(D('FUser')->errMsg);
			}

			//判断是否需要更改关系链
			$relaInfo 	= D('FUser')->getRelaInfo($userId);
			if($relaInfo['father_id'] != $fatherId){
				if(!D('FUser')->changeRelaInfo($userId, $fatherId)){
					E(D('FUser')->errMsg);
				}
			}

			//事务提交
			$model->commit();
		}catch(\Exception $e){
			$model->rollback();
			$this->response($e->getMessage(), 0);
		}

		$this->response([
			'role_id'	=> $roleId,
			'father_id'	=> $fatherId,
			'mobile'	=> $mobile
		]);

	}

	/**
	 * 更改用户信息
	 * @param 	$user_id
	 * @param 	$user_info
	 * @return  boolean
	 */
	function updateItem(){
		$this->unEmptyParam(['user_id', 'user_info']);
		
		$userId 	= $this->request('user_id');
		$userInfo 	= $this->request('user_info');

		//VIP到期时间处理
		if($userInfo['vip_enddate']){
			$userInfo['vip_endtime']	= strtotime($userInfo['vip_enddate']);
		}

		if($userInfo['child_birthday_date'])
			$userInfo['child_birthday']	= strtotime($userInfo['child_birthday_date']);

		$result 	= D('FUser')->changeUserInfo($userId, $userInfo);
		if($result === false)
			$this->outOInfo(D('FUser')->errMsg, -1);
		$this->outOInfo();
	}
	/**
	 * 导出相关数据
	 * @param string $keyword 关键词
	 * @param int $fatherId 父ID
	 * @param string $sort 排序字段
	 * @param int $desc 是否倒序
	 * @return list
	 */
	function outExcel(){
		$this->unEmptyParam(array('start', 'length'));
		$keyword 	= $this->iInfo['keyword'];
		$fatherId 	= $this->iInfo['father_id'];
		$sort 	= $this->iInfo['sort'];
		$desc 	= $this->iInfo['desc'];
		$start 	= $this->iInfo['start'];
		$length 	= $this->iInfo['length'];
		$timeS 	= $this->request('date_start') ? strtotime($this->request('date_start')) : false;
		$timeE 	= $this->request('date_end') ? strtotime($this->request('date_end')) + 3600*24 : false;

		$list 	= D('FUser')->getExcelList($timeS, $timeE, $fatherId, $keyword, $start, $length, $sort, $desc, $count);
		$title 	= array(
			'用户ID', '真实姓名', '微信昵称', '手机号码', '用户角色',
			'性别', '累计金额', '钱包余额', '积分', 
			'发展人数', '国家', '省份', '城市', '学校名称', '学生数量', '教师数量',
			'VIP等级', 'VIP到期时间'
		);

		$roleMap 	= BaseFUserModel::ROLE_MAP;
		foreach($list as &$user){
			$u['id']	= $user['id'];
			$u['truename']	= $user['truename'];
			$u['nickname']	= $user['nickname'];
			$u['mobile']	= $user['mobile'];
			$u['role']	= $roleMap[$user['role_id']];
			$u['sex']	= C('MEMBER_SEX.'.$user['sex']);
			$u['amount']	= $user['amount'];
			$u['wallet']	= $user['wallet'];
			$u['score']	= $user['score'];
			$u['develop_count']	= $user['develop_count'];
			$u['country']	= $user['country'];
			$u['province']	= $user['province'];
			$u['city']	= $user['city'];
			$u['school_name']	= $user['school_name'];
			$u['school_students']	= $user['school_students'];
			$u['school_teachers']	= $user['school_teachers'];
			$u['vip_level']	= $user['vip_level'];
			$u['vip_enddate']	= date('Y-m-d', $user['vip_endtime']);
			$user 	= $u;
		}
		$excelName 	= 'user_list_'.$start;
		out_excel($title, $list, $excelName);
	}

	/**
	 * 获取导出数据总页数
	 * @param   $keyword 关键词
	 * @param   $fatherId 上级ID
	 * @return  list
	 */
	function outExcelCount(){
		$keyword 	= $this->iInfo['keyword'];
		$fatherId 	= $this->iInfo['father_id'];
		$timeS 	= $this->request('date_start') ? strtotime($this->request('date_start')) : false;
		$timeE 	= $this->request('date_end') ? strtotime($this->request('date_end')) + 3600*24 : false;
		$count 	= 'only';
		D('FUser')->getExcelList($timeS, $timeE, $fatherId, $keyword, 0, 0, 0, 0, $count);
		$this->outOInfo(array('count' => $count));
	}

	/**
	 * 获取VIP销售记录
	 * @param 	$date_start
	 * @param 	$date_end
	 * @param 	$p
	 * @return 	json $list
	 */
	function getVipBargainList(){
		$condition 	= $this->request('condition', []);
		$condition['goods_type']	= 5;
		$condition['status'] 	= 1;
		if(isset($condition['date_start']) && $condition['date_start']){
			$condition['time_start']	= strtotime($condition['date_start']);
		}
		if(isset($condition['date_end']) && $condition['date_end']){
			$condition['time_end'] 	= strtotime($condition['date_end']) + 3600 * 24;
		}
		$page 	= $this->request('p', 1);
		$pageHtml 	= true;
		$total 	= true;

		$list 	= D('Money')->getList($condition, $page, $pageHtml, $total);
		if($list === false)
			$this->response(D('Money')->errMsg, 0);

		$this->response([
			'list' => $list, 
			'page_html' => $pageHtml, 
			'total'	=> $total
		]);
	}

	/**
	 * 导出VIP销售记录
	 * @param 	$start
	 * @param 	$length
	 * @param 	$keyword
	 * @param 	$date_start
	 * @param 	$date_end
	 * @return  list or count(if no start)
	 */
	function outVipBargainExcel(){
		$start 	= $this->request('start');
		$length 	= $this->request('length');
		$timeS 	= $this->request('date_start') ? strtotime($this->request('date_start')) : false;
		$timeE 	= $this->request('date_end') ? strtotime($this->request('date_end')) + 3600 * 24 : false;
		$goodsType 	= 5;

		$result 	= D('Money')->outExcel($goodsType, $start, $length, $timeS, $timeE);
		if($result === false)
			$this->outOInfo(D('FUser')->errMsg, 0);

		if(is_numeric($result))
			$this->response([
				'count' => $result,
				'sql'	=> (new \Think\Model())->getLastSql(),
				'date_start'	=> $this->request('date_start')
			]);

		$title 	= ['订单ID', '用户ID', '订单号', '微信昵称', '真实姓名', '商品类型', '商品名称', '购买时间', '实际价格', 
		'购买价格', '平台利润', '分成金额'];

		$list 	= [];
		foreach($result as $item){
			$list[] 	= [
				$item['id'], $item['user_id'], $item['trade_no'], $item['nickname'], $item['truename'],
				$item['goods_type_text'], $item['goods_name'], date('Y-m-d H:i:s', $item['create_time']),
				$item['price'], $item['amount'], $item['profit'], $item['deduct']
			];
		}

		out_excel($title, $list, 'purcharse_vip_list_'.$start);
	}

	
	/**
	 * 导出VIP列表
	 * @param 	$keyword
	 * @param 	$start
	 * @param 	$lenght
	 * @return 	file or count
	 */
	function outVipExcel(){
		//客户端变量获取
		$keyword 	= $this->request('keyword');
		$start 		= $this->request('start');
		$length 	= $this->request('length');
		$sort 		= $this->request('sort');
		$desc 		= $this->request('desc');

		$result 	= D('FUser')->outVipExcel($keyword, $start, $length, $sort, $desc);
		if(is_numeric($result)){
			$this->outOInfo(['count' => $result]);
		}

		$title 	= [
			'用户ID', '微信昵称', '用户名', '真实姓名',
			'VIP等级', 'VIP到期时间', '关注时间'
		];
		foreach($result as &$user){
			$u['id']	= $user['id'];
			$u['nickname']	= $user['nickname'];
			$u['username']	= $user['username'];
			$u['truename']	= $user['truename'];
			$u['vip_level']	= $user['vip_level'];
			$u['vip_enddate']	= date('Y-m-d', $user['vip_endtime']);
			$u['subscribe_date']	= date('Y-m-d', $user['subscribe_time']);
			$user 	= $u;
		}

		out_excel($title, $result, 'vip_list_'.$start);
	}
}